namespace taurus.client {

    /**
     * LagMonitor
     */
    export class LagMonitor {
        private _averagePingTime: number;
        private _pollTimer: number;
        private _queueSize: number;
        private _interval: number;
        private _run: boolean;
        private _engine: SocketEngine;
        private _valueQueue: number[];
        private _write_queue: number[];

        public constructor(engine: SocketEngine, interval: number, queueSize: number) {
            if (interval < 1) {
                interval = 1;
            }
            this._engine = engine;
            this._valueQueue = [];
            this._write_queue = [];
            this._queueSize = queueSize;
            this._interval = interval * 1000;
            this._averagePingTime = 0;
        }

        public fnPingPong() {
            var item = 0;
            if(this._write_queue.length>0){
                let w_time = this._write_queue.pop();
                item = new Date().getTime() - w_time;
            }
            
            if (this._valueQueue.length >= this._queueSize) {
                this._valueQueue.splice(0, 1);
            }
            this._valueQueue.push(item);
            if (this._valueQueue.length == 0) {
                this._averagePingTime = 0;
            }
            var num = 0;
            for (var i = 0; i < this._valueQueue.length; ++i) {
                num += this._valueQueue[i];
            }
            this._averagePingTime =Math.floor(num / this._valueQueue.length);
        }

        /**
         * 启动监听
         */
        public start() {
            if (!this.isRunning()) {
                var self = this;
                self._run = true;
                self._engine._controller.sendPingPong();
                this._pollTimer = setInterval(function () {
                    self._engine._controller.sendPingPong();
                    self._write_queue.push(new Date().getTime());
                }, this._interval);
            }
        }

        /**
         * 停止监听
         */
        public stop() {
            if (this.isRunning()) {
                this._run = false;
                clearInterval(this._pollTimer);
            }
        }

        public destroy() {
            this.stop();
            this._engine = null;
        }

        /**
         * 平均Ping的时间
         * @return
         */
        public getAveragePingTime() {
            return this._averagePingTime;
        }

        public isRunning(): boolean {
            return this._run;

        }
    }
}